package rexsee.dialog;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.BrowserParent;
import rexsee.core.widget.DivDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.widget.LinearLayout;

public class PopupWindow extends DivDialog implements BrowserParent {

	public final LinearLayout mLayout;
	public final LinearLayout mTopLayout;
	public final LinearLayout mBottomLayout;

	public final Browser mChild;
	public final Runnable mClickCallback;

	public PopupWindow(Browser browser, String dialogId, String url, String style, Runnable clickCallback) {

		super(browser, dialogId, style);
		mClickCallback = clickCallback;

		mLayout = new LinearLayout(mContext);
		mLayout.setOrientation(LinearLayout.VERTICAL);
		mLayout.setBackgroundColor(Color.TRANSPARENT);

		mTopLayout = new LinearLayout(mContext);
		mTopLayout.setOrientation(LinearLayout.VERTICAL);
		mTopLayout.setBackgroundColor(Color.TRANSPARENT);
		mTopLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		mBottomLayout = new LinearLayout(mContext);
		mBottomLayout.setOrientation(LinearLayout.VERTICAL);
		mBottomLayout.setBackgroundColor(Color.TRANSPARENT);
		mBottomLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

		mChild = new Browser(mContext, browser, div, this);
		mChild.setStyle(style);
		mChild.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT, 1));

		mLayout.addView(mTopLayout);
		mLayout.addView(mChild);
		mLayout.addView(mBottomLayout);

		mChild.garbageCollector.stopAutoCollector();

		this.addChild(mLayout);
		this.setOnKeyListener(null);
		this.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface arg0) {
				destroy();
			}
		});
		if (url != null && !url.trim().equals("")) {
			if (styleSheet.label_type.equals("html")) {
				mChild.function.loadHTML(url);
			} else {
				String realUrl = mBrowser.urlListeners.getAbsoluteUrl(url);
				mChild.function.load(realUrl);
			}
		}

	}

	@Override
	protected void onClick(DialogInterface dialog) {
		if (mClickCallback != null) {
			mClickCallback.run();
		}
	}

	public Browser getBrowser() {
		return mChild;
	}

	@Override
	public String getParentId() {
		return this.getDialogId();
	}

	@Override
	public boolean isCancelable() {
		return styleSheet.window_cancelable.equalsIgnoreCase("true");
	}

	@Override
	public void doCancel() {
		this.dismiss();
	}

	public void destroy() {
		if (mChild != null) mChild.onDestroy();
	}

}
